package org.example.btchat;

import org.example.btchat.client.ClientService;
import org.example.btchat.server.ServerService;
import org.example.btchat.server.ServerService.LocalBinder;

import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.annotation.TargetApi;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class MainActivity extends Activity
{
	private BTChatInterface service;
	private ServiceConnection serviceConnection = new ServiceConnection()
	{
		public void onServiceConnected(ComponentName name, IBinder binder)
		{
			service = ((LocalBinder) binder).getService();
			
			service.setActivity(MainActivity.this);
			
			onServiceStarted();
			
			try
			{
				service.start();
			}
			catch(Exception e)
			{
				Toast.makeText(MainActivity.this, R.string.msg_no_connection, Toast.LENGTH_SHORT).show();
				finish();
			}
		}
		
		@Override
		public void onServiceDisconnected(ComponentName name)
		{
			MainActivity.this.finish();
		}
	};
	private LinearLayout viewMessages;
	
	private EditText viewNewMessage;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activity_main, menu);
		return true;
	}
	
	public void onMessageReceive(final Message msg)
	{
		this.runOnUiThread(new Runnable()
		{
			@Override
			public void run()
			{
				TextView tv = new TextView(MainActivity.this);
				tv.setText(Html.fromHtml("<strong>" + msg.getSource() + "</strong>: "));
				tv.append(msg.getMessage());
				
				viewMessages.addView(tv);
			}
		});
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		// Handle item selection
		switch(item.getItemId())
		{
			case R.id.menu_make_discoverable:
				make_discoverable();
				return true;
			default:
				return super.onOptionsItemSelected(item);
		}
	}
	
	private void make_discoverable()
	{
		Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
		intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
		startActivity(intent);
	}
	
	private void onServiceStarted()
	{
		viewNewMessage.setOnEditorActionListener(new OnEditorActionListener()
		{
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
			{
				Log.v("onEditorAction", String.format("actionId: %d", actionId));
				
				boolean handled = false;
				if(actionId == EditorInfo.IME_ACTION_SEND)
				{
					String source = service.getName();
					String message = viewNewMessage.getText().toString();
					viewNewMessage.setText("");
					
					service.sendMessage(new Message(source, message));
					handled = true;
				}
				return handled;
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if(requestCode == BTChat.REQUEST_ENABLE_BT)
		{
			service.onActivityResult(requestCode, resultCode, data);
		}
		if(requestCode == BTChat.REQUEST_SELECT_DEVICE)
		{
			Intent in;
			if(data.getBooleanExtra("server", true))
			{
				in = new Intent(this, ClientService.class);
				in.putExtra("device", data.getStringExtra("device"));
			}
			else
				in = new Intent(this, ServerService.class);
			
			bindService(in, serviceConnection, Context.BIND_AUTO_CREATE);
		}
	}
	
	@Override
	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
			getActionBar().setHomeButtonEnabled(false);
		
		Intent intent = new Intent(MainActivity.this, SelectDevice.class);
		startActivityForResult(intent, BTChat.REQUEST_SELECT_DEVICE);
		
		viewNewMessage = (EditText) findViewById(R.id.newmessage);
		viewMessages = (LinearLayout) findViewById(R.id.messages);
	}
}
